package com.api.workflow.web;

import com.alibaba.fastjson.JSONObject;
import com.api.workflow.util.YNHttpUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.text.SimpleDateFormat;
import java.util.*;

/*
 *OA-10.员工借款审批申请
 * 接口5 OA与SAP付款申请接口
 */
public class YN10FII002ActionN extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        //初始化日志记录
        BaseBean baseBean = new BaseBean();
        String requestid = requestInfo.getRequestid();
        String lcbh = requestInfo.getWorkflowid();
        //获取表单ID并取绝对值
        int formid = requestInfo.getRequestManager().getFormid();
        int formidAbs = Math.abs(formid);// 流程表单id绝对值
        String tableName = "formtable_main_" + formidAbs;
        // 主表数据
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        Property[] property = mainTableInfo.getProperty();
        //这里是存储了主表全部的数据  可自行修改存储结构
        Map<String, Object> mainTableInfoMap = new HashMap<>();
        List<Map<String, Object>> mainTableMap = getMaps(requestInfo);
        for (int i = 0; i < property.length; i++) {
            String name = property[i].getName().toLowerCase();
            mainTableInfoMap.put(name, Util.null2String(property[i].getValue()));
        }
        //记录主表日志
        baseBean.writeLog("lyh:OA-10=============mainTableInfoMap:" + JSONObject.toJSONString(mainTableInfoMap));

        //明细表数据
        List<Map<String, Object>> detailTableMap = getMaps(requestInfo);
        //业务逻辑
        try {
            RecordSet rs = new RecordSet();
            Map<String, Object> map = new HashMap<>();
            //ZYF
            String zyf = String.valueOf(mainTableInfoMap.get("zyf"));
            map.put("ZSFFK", "N");

            map.put("ZBONO", mainTableInfoMap.get("lcbh"));
            map.put("ZREID", requestid);
            //获取申请部门ID
            String sqr = mainTableInfoMap.get("sqr").toString();
            String sql1 = "select * from hrmresource where id = '" + sqr + "'";
            String departmentid = " ";
            baseBean.writeLog("lyh:OA-10================sql1" + sql1);
            rs.execute(sql1);
            if (rs.next()) {
                map.put("ZHRNO", rs.getString("workcode"));
                map.put("ZNAME", rs.getString("lastname"));
                departmentid = rs.getString("departmentid");
                baseBean.writeLog("lyh:OA-10=============ZHRNO" + rs.getString("workcode") + "ZNAME" + rs.getString("lastname"));
            }
            map.put("ZBOTYP", "Z02");
            map.put("LIFNR", mainTableInfoMap.get("skrygbm"));
            //付款方式
            map.put("ZLSCH", mainTableInfoMap.get("fkfs"));
            map.put("WAERS", mainTableInfoMap.get("hb"));
            map.put("BUKRS", mainTableInfoMap.get("gsdm"));
            map.put("ZAPDAT", mainTableInfoMap.get("sqrq"));
            //设置当前日期为审批日期
            Date currentDate = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = dateFormat.format(currentDate);
            map.put("ZPASSDAT", formattedDate);
            map.put("ZBKTXT", mainTableInfoMap.get("jksm"));
            map.put("ZAZBET", mainTableInfoMap.get("jkje"));
            map.put("BKVID", mainTableInfoMap.get("yxbs"));
            map.put("ZPARBANKL", mainTableInfoMap.get("skzhlxh"));
            map.put("ZPARBANKN", mainTableInfoMap.get("skrzh"));
            map.put("ZPARKOINH", mainTableInfoMap.get("zhcyr"));
            map.put("ZPARBANKA", mainTableInfoMap.get("zhmc"));

            //通过申请部门ID查询部门信息
            String sql2 = "select * from hrmdepartment where id = '" + departmentid + "'";
            baseBean.writeLog("lyh:OA-10==============sql2" + sql2);
            rs.execute(sql2);
            if (rs.next()) {
                map.put("ZSQBM", rs.getString("departmentcode"));
                map.put("ZBMMS", rs.getString("departmentname"));
                baseBean.writeLog("lyh:OA-10============ZSQBM" + rs.getString("departmentcode") + "ZBMMS:" + rs.getString("departmentname"));
            }
            //处理明细表数据
            Map<String, Object> ITEM = new HashMap<>();
            ArrayList<Map> list = new ArrayList<>();


            ITEM.put("BUZEI", 1);
            ITEM.put("WRBTR", mainTableInfoMap.get("jkje"));
            ITEM.put("KOSTL", mainTableInfoMap.get("cbzx"));
            ITEM.put("ZEXTYPE", mainTableInfoMap.get("fylx"));
            list.add(ITEM);

            map.put("ITEMS", list);
            //将Map转为JSON对象并记录日志
            JSONObject object = new JSONObject(map);
            baseBean.writeLog("lyh:OA-10============object" + object.toJSONString());
            //调用HTTP工具发送请求
            String post = YNHttpUtils.FII002(object.toJSONString(), YNHttpUtils.token());
            baseBean.writeLog("lyh:OA-10============post" + post);
            JSONObject jsonObject = JSONObject.parseObject(post);
            //String STATUS = jsonObject.getString("STATUS");
            //String MESSAGE = jsonObject.getString("MESSAGE");

            JSONObject jsonObject1 = jsonObject.getJSONObject("RETURN");
            String MESSAGE = jsonObject1.getString("MESSAGE");
            String STATUS = jsonObject1.getString("STATUS");
            RecordSet recordSet = new RecordSet();

            //修改主表参数
            String updateMainTableName = "update " + tableName + " set qqcs = ? , fhjg = ?,qqn=?,fhn=?  where  requestid = ? ";
            recordSet.executeUpdate(updateMainTableName, object.toString(), post, object.toString(), post, requestid);
            baseBean.writeLog("wyq===OA-10=======updateMainTableName" + updateMainTableName);

            if (!"S".equals(STATUS)) {
                requestInfo.getRequestManager()
                        .setMessageid(requestInfo.getRequestid() + "OA-10");
                requestInfo.getRequestManager().setMessagecontent("SAP接口异常，请联系SAP人员，错误信息提示:" + MESSAGE);
                return Action.FAILURE_AND_CONTINUE;
            }

            String SAPPZH = jsonObject1.getString("BELNR");
            String update = "update " + tableName + " set sappzh = '" + SAPPZH + "' where requestid = '" + requestid + "'";
            baseBean.writeLog("wyq===OA-10============update" + update);
            rs.executeUpdate(update);


        } catch (Exception e) {
            baseBean.writeLog("wyq===OA-10======exc" + e.toString());
            requestInfo.getRequestManager()
                    .setMessageid(requestInfo.getRequestid() + "OA-10");
            requestInfo.getRequestManager().setMessagecontent("OA接口异常：" + e.toString());
            return Action.FAILURE_AND_CONTINUE;
        }

        return Action.SUCCESS;
    }

    /**
     * 提取明细表全部的数据
     *
     * @param requestInfo
     * @return
     */
    private static List<Map<String, Object>> getMaps(RequestInfo requestInfo) {
        DetailTable[] detailTable = requestInfo.getDetailTableInfo().getDetailTable();
        //这里是存储了全部的明细表数据  可自行修改存储结构
        List<Map<String, Object>> detailTableMap = new ArrayList<>();
        if (detailTable.length > 0) {
            for (int i = 0; i < detailTable.length; i++) {
                DetailTable dt = detailTable[i];
                Row[] s = dt.getRow();
                for (int j = 0; j < s.length; j++) {
                    Row r = s[j];
                    Cell c[] = r.getCell();
                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                    for (int k = 0; k < c.length; k++) {
                        Cell c1 = c[k];
                        String name = c1.getName().toLowerCase();
                        String value = c1.getValue();
                        objectObjectHashMap.put(name, value);
                    }
                    detailTableMap.add(objectObjectHashMap);
                }
            }
        }
        return detailTableMap;
    }
}
